package cn.dwhalse.codegen.service.impl;

import cn.dwhalse.codegen.entity.GenConfig;
import cn.dwhalse.codegen.mapper.GeneratorMapper;
import cn.dwhalse.codegen.service.GeneratorService;
import cn.dwhalse.codegen.util.CodeGenUtils;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * @author Jencks.Gao
 * @date 2020-11-30
 * <p>
 * 代码生成器
 */
@Service
@RequiredArgsConstructor
public class GeneratorServiceImpl implements GeneratorService {

	private final GeneratorMapper generatorMapper;

	/**
	 * 生成代码
	 * @param genConfig 生成配置
	 * @return
	 */
	@Override
	public byte[] generatorCode(GenConfig genConfig) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);

		String tableNames = genConfig.getTableName();
		for (String tableName : StrUtil.split(tableNames, StrUtil.DASHED)) {
			// 查询表信息
			Map<String, String> table = generatorMapper.queryTable(tableName);
			// 查询列信息
			List<Map<String, String>> columns = generatorMapper.queryColumns(tableName, genConfig.getDsName());
			// 生成代码

			CodeGenUtils.generatorCode(genConfig, table, columns, zip);
		}
		IoUtil.close(zip);
		return outputStream.toByteArray();
	}
}
